# auth.py
from flask import Blueprint, jsonify, request
from flask_jwt_extended import (
    unset_jwt_cookies, get_jwt_identity, jwt_required)
import flaskapp.services.user as userService
import logging

logger = logging.getLogger(__name__)
user_bp = Blueprint('user', __name__)


@user_bp.route('/api/user', methods=["POST"])
@jwt_required()
def createUser():
    try:
        current_user = get_jwt_identity()
        print(request.json)
        id = request.json.get("id", None)
        username = request.json.get("username", None)
        password = request.json.get("password", None)
        telephone = request.json.get("telephone", None)
        email = request.json.get("email", None)
        ret = userService.exist(username)
        if ret == 1:
            userService.update(id,
                username=username, password=password, telephone=telephone, email=email)
            pass
        else:
            ret = userService.insert(
                username=username, password=password, telephone=telephone, email=email)

        response = jsonify({"code": 0, "message": ret})
        return response
    except Exception as e:
        logger.error(f"Error getting data: {e}")
        return jsonify({"code": -1, "message": e.args})


@user_bp.route('/api/user', methods=["GET"])
@jwt_required()
def getUser():
    try:
        # current_user = get_jwt_identity()
        # print(current_user)
        ret = userService.get()
        response = jsonify({"code": 0, "data": ret})
        return response
    except Exception as e:
        logger.error(f"Error getting data: {e}")
        return jsonify({"code": -1, "message": e.args})


@user_bp.route('/api/user/info', methods=["GET"])
@jwt_required()
def userInfo():
    try:
        # current_user = get_jwt_identity()
        # print(current_user)
        ret = userService.findOne(request.values.get('username'))
        response = jsonify({"code": 0, "data": ret.to_dict()})
        return response
    except Exception as e:
        logger.error(f"Error getting data: {e}")
        return jsonify({"code": -1, "message": e.args})


@user_bp.route('/api/user/<id>', methods=["DELETE"])
@jwt_required()
def deleteUser(id: str):
    try:
        # current_user = get_jwt_identity()
        ret=userService.delete(id)
        response = jsonify({"code": 0,"message":"success","data":ret})
        return response
    except Exception as e:
        logger.error(f"Error getting data: {e}")
        return jsonify({"code": -1, "message": e.args})
